<template>
    <div>
        <!-- <My-Tabbar></My-Tabbar> -->
        <van-nav-bar title="信息录入" />

        <van-form @submit="formSubmit" style="width: 100%;">
            <van-cell-group>
                <van-field required link-type="navigateTo" url="" title-width="4em" name="uname" label="姓名"
                    v-model="datainfo.uname" placeholder="请输入真实姓名" />
                <van-field required readonly title-width="4em" name="sex" label="性别" v-model="company.sex"
                    placeholder="请选择性别" @click-input="selectSex" />
                <van-field required readonly title-width="4em" name="iid" label="公司" v-model="company.company"
                    placeholder="请选择公司" @click-input="selectCompany" />
                <van-field required readonly title-width="4em" name="section" label="所在部门" v-model="company.section"
                    placeholder="请选择部门" @click-input="selectSectionCompany" />
                <van-field required readonly title-width="4em" name="position" label="所属岗位" v-model="company.position"
                    placeholder="请选择岗位" @click-input="selectPositionCompany" />

                <van-field required readonly title-width="4em" name="inGroup" label="所属小组" v-model="company.inGroup"
                    placeholder="请选择小组" @click-input="selectGroupCompany" />

                <van-field required title-width="4em" name="phone" label="手机号码" v-model="datainfo.phone"
                    placeholder="请输入手机号码" />
                <van-field required title-width="4em" name="email" label="邮箱地址" v-model="datainfo.email"
                    placeholder="请输入邮箱地址" />
                <van-field readonly required title-width="4em" name="joinTime" v-model="date" label="入职时间"
                    placeholder="请选择入职时间" @click-input="bindClickInputTime" />

            </van-cell-group>
            <!-- <view wx:for="{{5}}" style="display: flex;flex-direction: row;">
    <van-uploader file-list="{{ fileList }}" deletable="{{ true }}" />
  </view> -->
            <van-cell-group :border="false">
                <!-- <van-cell title="提示" label="请将信息填写完整！" :border="false" /> -->
                <van-cell title="审核信息" title-style="color:red;" :label="company.remark" :border="false"
                    v-if="company.remark != '无'" />
            </van-cell-group>
            <div style="width: 100%;display: flex;align-items: center;justify-content: center;margin-top: 20px;">
                <div style="width: 95%;">
                    <van-button round type="info" native-type="submit" size="large">
                        下一步
                    </van-button>
                </div>
            </div>
            <div style="height: 20rpx;">

            </div>
        </van-form>

        <!-- <van-calendar v-model:show="showCalendar" :min-date="minDate" @close="onCloseCalendar"
            @confirm="onConfirmCalendar" /> -->
        <van-popup v-model:show="showCalendar" round position="bottom" @close="onCloseSexPopup">
            <van-datetime-picker v-model="currentDate" type="date" title="选择日期" :min-date="minDate" :max-date="maxDate"
                @confirm="onConfirmCalendar" @cancel="onCloseCalendar" />
        </van-popup>

        <van-popup v-model:show="showPopupSex" round position="bottom" @close="onCloseSexPopup">
            <van-picker show-toolbar title="选择性别" :columns="sexs" @cancel="onCancelSexPicker"
                @confirm="onConfirmSexPicker" />
        </van-popup>

        <van-popup v-model:show="showPopup" round position="bottom" custom-style="height: 60%;width:100%"
            @close="onClosePopup">
            <van-picker show-toolbar title="选择公司" :columns="pickerColumns" @cancel="onCancelPicker"
                @confirm="onConfirmPicker" />
        </van-popup>

        <van-popup v-model:show="showPopupSection" round position="bottom" custom-style="height: 60%;width:100%"
            @close="onCloseSectionPopup">
            <van-picker show-toolbar title="选择部门" :columns="pickerSectionColumns" @cancel="onCancelSectionPicker"
                @confirm="onConfirmSectionPicker" />
        </van-popup>

        <van-popup v-model:show="showPopupGroup" round position="bottom" custom-style="height: 60%;width:100%"
            @close="onCloseGroupPopup">
            <van-picker show-toolbar title="选择小组" :columns="pickerGroupColumns" @cancel="onCancelGroupPicker"
                @confirm="onConfirmGroupPicker" />
        </van-popup>

        <van-popup v-model:show="showPopupPosition" round position="bottom" custom-style="height: 60%;width:100%"
            @close="onClosePositionPopup">
            <van-picker show-toolbar title="选择岗位" :columns="pickerPositionColumns" @cancel="onCancelPositionPicker"
                @confirm="onConfirmPositionPicker" />
        </van-popup>
        <van-dialog v-model:show="showDialog" title="提示">
            <div style="height: 50px; display: flex;justify-content: center;align-items: center;margin: 15px;">
                <label>{{ hint }}</label>
            </div>

        </van-dialog>
    </div>
</template>
  
<script>
import { Toast } from 'vant';

// import FingerprintJS from '@fingerprintjs/fingerprintjs' // 引入获取浏览器标识
// import { formatDate } from "@/filters/index";

export default {
    name: 'Home',
    components: {

    },
    data() {

        return {
            minDate: new Date(2006, 1, 1),
            maxDate: new Date(2050, 5, 1),
            showCalendar: false,
            date: new Date(2006, 1, 1),
            currentDate: ['2021', '01', '01'],
            companys: [],
            company: {},
            sexs: ["男", "女"],
            showPopupSex: false,
            pickerColumns: [],
            showPopup: false,
            datainfo: {},
            showPopupSection: false,
            pickerSectionColumns: [],
            sections: [],
            section: {},
            pickerGroupColumns: [],
            showPopupGroup: false,
            groups: [],
            group: {},
            showPopupPosition: false,
            pickerPositionColumns: [],
            positions: [],
            position: {},
            visitorId: '',
            code: '',
            showDialog: false,
            hint: '',
            // fileImgList: [],
            // fileImgCards: [],
        }
    },
    methods: {

        getCode() {
            // 非静默授权，第一次有弹框
            const code = this.getUrlParam("code"); // 截取路径中的code，如果没有就去微信授权，如果已经获取到了就直接传code给后台获取openId
            const local = window.location.href;
            // var local = "https://auth.sjht.com/user/get/code/userid"
            const APPID = "ww930d12930d5cc0d3"; // 企业微信
            // const APPID = 'wx33cc3c3bc173a38d'
            // const APPID = '1000019'

            console.log(code);
            this.code = code
            if (code == null || code == "") {
                window.location.href =
                    "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" +
                    APPID +
                    "&redirect_uri=" +
                    encodeURIComponent(local) +
                    "&response_type=code&scope=snsapi_base&state=STATE&agentid=1000020#wechat_redirect";
            } else {
                console.log(code);
                this.code = code
                this.getOpenId(code); //把code传给后台获取用户信息
            }
        },
        getUrlParam(name) {
            var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");

            var r = window.location.search.substr(1).match(reg);
            console.log(r);

            if (r != null) return unescape(r[2]);

            return null;
        },

        async getOpenId(code) {
            // 通过code获取 openId等用户信息，/api/user/wechat/login 为后台接口
            let _this = this;
            console.log(code);
            // var res1 = await this.$api.user.getAccessToken();
            // this.accessToken = res1.data
            var res = await this.$api.user.getUserUserId("accessToken", code)
            // await this.$api.user.getUserAuth()
            window.sessionStorage.setItem('openid', JSON.stringify(res.data))
            this.getOpenidInfo(res.data,null)
            console.log(res);
        },

        // 获取设备或浏览器唯一标识
        // async getvisitorId() {
        //     const fp = await FingerprintJS.load()
        //     const result = await fp.get()
        //     const visitorId = result.visitorId
        //     this.visitorId = visitorId
        //     console.log('唯一标识', visitorId)
        // },

        async getAllCompany() {
            let res = await this.$api.user.getUserCompanys()
            console.log(res);
            var pickerColumns = []
            res.data.forEach(item => {
                pickerColumns.push(item.cname)
            })
            this.pickerColumns = pickerColumns
            this.companys = res.data
            console.log(this.companys);

        },

        selectSex() {
            this.showPopupSex = true

        },
        onConfirmSexPicker(value, index) {
            var that = this
            var company = this.company
            company.sex = value
            this.company = company
            this.showPopupSex = false

        },
        onCancelSexPicker() {
            this.showPopupSex = false

        },
        onCloseSexPopup() {
            this.showPopupSex = false
        },
        selectCompany() {
            this.showPopup = true

        },
        async onConfirmPicker(value, index) {
            var that = this
            var values = this.companys[index]
            var company = this.company

            company.iid = values.iid
            company.company = value
            company.section = ''
            company.position = ''
            company.inGroup = ''
            console.log(value, index)

            var res = await this.$api.user.getUserSections(values.iid)
            console.log(res);
            var pickerSectionColumns = []
            res.data.forEach(item => {
                pickerSectionColumns.push(item.section)
            })
            this.pickerSectionColumns = pickerSectionColumns
            this.sections = res.data
            this.company = company
            this.showPopup = false


        },
        onClosePopup() {
            this.showPopup = false

        },
        onCancelPicker() {
            this.showPopup = false

        },
        selectSectionCompany() {
            if(this.pickerSectionColumns.length<1){
                Toast("请先选择公司！")
                return
            }
            this.showPopupSection = true

        },
        async onConfirmSectionPicker(value, index) {
            var that = this

            var values = this.sections[index]
            var company = this.company
            if (!values) {

                return
            }
            company.section = value
            company.position = ''
            company.inGroup = ''
            console.log(index, value)

            var res = await this.$api.user.getUserPositions(values.id)
            console.log(res);
            var pickerPositionColumns = []
            res.data.forEach(item => {
                pickerPositionColumns.push(item.position)
            })
            this.pickerPositionColumns = pickerPositionColumns
            this.positions = res.data
            this.company = company
            this.showPopupSection = false


        },
        onCancelSectionPicker() {
            this.showPopupSection = false

        },
        onCloseSectionPopup() {
            this.showPopupSection = false
        },

        selectPositionCompany() {
            if(this.pickerPositionColumns.length<1){
                Toast("请先选择部门！")
                return
            }
            this.showPopupPosition = true

        },
        async onConfirmPositionPicker(value, index) {
            var that = this

            var values = this.positions[index]
            var company = this.company
            if (!values) {

                return
            }
            company.position = value
            company.inGroup = ''
            console.log(index, value)

            var res = await this.$api.user.getUserGroups(values.id)
            console.log(res);
            var pickerGroupColumns = []
            res.data.forEach(item => {
                pickerGroupColumns.push(item.inGroup)
            })
            this.pickerGroupColumns = pickerGroupColumns
            this.groups = res.data
            this.company = company
            this.showPopupPosition = false

        },
        onCancelPositionPicker() {
            this.showPopupPosition = false
        },
        onClosePositionPopup() {
            this.showPopupPosition = false

        },

        selectGroupCompany() {
            if(this.pickerPositionColumns.length<1){
                Toast("请先选择岗位！")
                return
            }
            this.showPopupGroup = true

        },
        onConfirmGroupPicker(value, index) {
            var company = this.company
            company.inGroup = value
            console.log(index, value)
            this.company = company
            this.showPopupGroup = false


        },
        onCancelGroupPicker() {
            this.showPopupGroup = false

        },
        onCloseGroupPopup() {
            this.showPopupGroup = false

        },

        bindClickInputTime() {
            this.showCalendar = true
            console.log(this.showCalendar)

        },
        onCloseCalendar() {
            this.showCalendar = false

        },
        formatDateCalendar(date) {
            // var times = formatDate(newDate)
            // console.log(times);
            date = new Date(date);
            return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;

        },
        showTime() {
            var date = new Date();
            var formData = `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`
            this.date = formData
            this.currentDate = date

        },
        onConfirmCalendar(event) {
            var date = this.formatDateCalendar(event)
            console.log(date);
            this.date = date
            this.showCalendar = false

        },

        async getOpenidInfo(openid,datainfo) {
            console.log(datainfo);
            if (datainfo != null) {
                datainfo.openid = openid
                this.datainfo = datainfo
                this.company = datainfo
            } else {
                var res = await this.$api.user.getOpenidInfo(openid)
                console.log(res)
                if (res.data != null) {
                    console.log('res.data不等于null')
                    this.datainfo = res.data
                    this.company = res.data
                    var company = this.company
                    company.openid = openid
                    this.company = company
                    console.log(res.data.infoCheck);
                } else {
                    console.log('res.data等于null')
                    this.datainfo = { openid: openid, remark: '无' ,infoCheck:'3'}
                    this.company = { openid: openid, remark: '无' ,infoCheck:'3'}
                }
                console.log(this.datainfo);
                if (this.datainfo.infoCheck === "2") {
                    this.showDialog = true
                    this.hint = '您的信息未通过审核，请重新完善，详情可查看下方提示信息或邮箱信息！'
                }

            }

        },
        formSubmit(data) {
            // var data = e.detail.value
            var that = this
            var company = this.company
            data.iid = company.iid
            data.openid = company.openid
            data.company = company.company
            data.remark = company.remark
            console.log(data);
            window.sessionStorage.clear()
            window.sessionStorage.setItem('datainfo', JSON.stringify(data))
            // console.log(this.fileImgList);
            var hint = '1'
            if (company.infoCheck === "0") {
                hint = '正在审核中,不可重复提交！'
            } else if (company.infoCheck === "1") {
                hint = '审核已通过，不可再提交！'
            }
            for (const [key, value] of Object.entries(data)) {
                console.log(key, value);
                if (value.trim() === "") {
                    hint = "请将信息填写完整！"
                }
            }
            if (hint != '1') {
                Toast(hint)
                return
            }
            this.$router.push({
                name: 'Faceimg',
                // params: { fileImgList: that.fileImgList, fileImgCards: that.fileImgCards },
            })

        },
    },
    activated() {
        console.log('----created----')
        console.log('创建成功')	//msg
        var datainfo = JSON.parse(window.sessionStorage.getItem('datainfo'))

        // console.log(datainfo);
        if (datainfo != null) {
            this.getOpenidInfo(datainfo.openid,datainfo)
        } else {
            this.getCode()
        }
        // this.getOpenId("123456789")
        // this.getvisitorId()
        // this.getOpenidInfo("12456",datainfo)
        this.getAllCompany()
        this.showTime()
        // var fileImgList = this.$route.params.fileImgList
        // var fileImgCards = this.$route.params.fileImgCards
        // if (fileImgList != null) {
        //     console.log("null");
        //     this.fileImgList = fileImgList
        //     // this.fileImgs = fileImgList
        //     this.fileImgCards = fileImgCards
        // }
    },
    // activated() {
    //     // if (!this.$route.meta.isBack) {
    //     // 如果isBack是false，表明需要获取新数据，否则就不再请求，直接使用缓存的数据 this.getData();
    //     var datainfo = JSON.parse(window.sessionStorage.getItem('datainfo'))
    //     // console.log(data.openid);
    //     if (datainfo != null) {
    //         this.getOpenidInfo(datainfo.openid,datainfo)
    //         console.log(datainfo);
    //     }
    //     // }
    //     // 恢复成默认的false，避免isBack一直是true，导致下次无法获取数据 this.$route.meta.isBack=false

    // },
}
</script>
  
<style lang="less"></style>
  